package com.example.wwk.graduationpractice.Activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.example.wwk.graduationpractice.Bean.MaxQuestionIdBean;
import com.example.wwk.graduationpractice.Bean.QuestionBean;
import com.example.wwk.graduationpractice.NetDataUtils.DynamicDataUtils;
import com.example.wwk.graduationpractice.Globalutils.ActivityCollector;
import com.example.wwk.graduationpractice.Globalutils.MyApplication;
import com.example.wwk.graduationpractice.Globalutils.PromptShowUtils;
import com.example.wwk.graduationpractice.Globalutils.SharedPreferenceUtils;
import com.example.wwk.graduationpractice.Globalutils.TimeUtils;
import com.example.wwk.graduationpractice.R;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;

public class QuizActivity extends AppCompatActivity implements View.OnClickListener {
    //back
    private ImageView back;
    //记住草稿
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    private String question;        //问题文稿
    //editText
    private EditText input;
    //intent的传值
    private String thisUser;
    //button 发表
    private Button publish;

    //smack 建立消息通道
    private AbstractXMPPConnection connection;
    private static ChatManager chatManager;
    private static Chat chat;
    //question的接收者
    private static final String questionReceiver = "question";
    //获取数据库所有问题id的最大值
    private int MaxQuestionId;
    //handler
    private Handler   handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                //网络请求获取数据库所有问题id的最大值
                case DynamicDataUtils.GET_MAXQUESTIONID_SUCCESS:
                    MaxQuestionIdBean maxQuestionIdBean = (MaxQuestionIdBean)msg.obj;
                    MaxQuestionId = maxQuestionIdBean.getMaxid();
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.quiz_activity);
        setTitle("");
        ActivityCollector.addActivity(this);
        //intent
        Intent intent = getIntent();
        thisUser = intent.getStringExtra("thisuserName");        //获取当前用户的用户名
        //input
        input = (EditText) findViewById(R.id.input);
        //记住草稿
        pref = SharedPreferenceUtils.getSharedPreferences();
        editor = SharedPreferenceUtils.getSharedEditor();
        getQuestion();      //获得之前保存的问题草稿
        //back
        back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(this);
        //toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //button 发表
        publish = (Button) findViewById(R.id.publish);
        publish.setOnClickListener(this);
        //smack connection，建立消息通道
        connection = MyApplication.getConnection();//全局连接
        chatManager = ChatManager.getInstanceFor(connection);      //获取实例
        chat = chatManager.createChat(questionReceiver + "@" + connection.getServiceName());   //为发送信息(问题)建立聊天通道
        //获得问题的最大questionId
        DynamicDataUtils.getMaxQuestionId(handler);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);

    }
    /*
    * 返回发表的问题，用于传递到上一个页面，显示
    * @param String name
    * @param String content
    * return QuestionBean
    */
    private QuestionBean returnResult(String name, String content) {
        String time = TimeUtils.getTime();
        QuestionBean questionBean = new QuestionBean(MaxQuestionId+1,name, time, content);
        return questionBean;
    }
    /*
    * 对话框，处理是否保存草稿
    */
    public boolean showDialog(final String questions, Context context) {
        MaterialDialog materialDialog;
        materialDialog = new MaterialDialog.Builder(context)
                .title("提示")
                .content("是否保存草稿？")
                .positiveText("保存")
                .negativeText("不保存")
                .onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            editor.putString("thisUser", thisUser);
                            editor.putString("question", questions);  //保存输入的草稿
                            editor.apply();
                            finish();
                        } else if (which == DialogAction.NEGATIVE) {    //不保存
                            editor.putString("thisUser", thisUser);
                            editor.putString("question", "");
                            editor.apply();
                            finish();
                        }
                    }

                })
                .show();

        if (materialDialog.isCancelled())
            return true;
        else
            return false;
    }
    /*
    获得之前保存的问题草稿
     */
    private void getQuestion() {
        String user = pref.getString("thisUser", "");
        if (user != null) {
            if (thisUser.equals(user)) {
                question = pref.getString("question", "");
                if (question != null && !question.equals("")) {
                    input.setText(question);
                }
            }
        }
    }
    /*
    * 通过消息通道发送问题
    */
    private void questionSend(String questionContent, Chat chat) {
        try {
            chat.sendMessage(questionContent);
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
            PromptShowUtils.showToast("问题发表失败！");
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                //对话框是否显示
                question = input.getText().toString();
                boolean flag;
                if (!question.equals("")) {//输入内容不为空
                    flag = showDialog(question, QuizActivity.this);
                } else
                    flag = true;
                if (flag)
                    finish();
                break;
            case R.id.publish:
                //发表问题
                editor.putString("user", thisUser);
                editor.putString("question", "");
                editor.apply();
                question = input.getText().toString();
                if (!"".equals(question)) {   //  问题不为空
                    questionSend(question,chat);        //将发表的问题发送给openfire
                    //将发表的问题返回给上一个页面，用于显示
                    QuestionBean questionBean = returnResult(thisUser, question);
                    Intent intent = new Intent();
                    intent.putExtra("questionBean", questionBean);
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    PromptShowUtils.showToast("问题不能为空！");
                }
                break;
        }

    }


}
